<?php

namespace apiend\models;

use Yii;
use common\base\Model;
use apiend\models\User;

/**
 * 找回密码
 * ForgetForm 
 */
class ResetPasswordForm extends Model {

    public $reset_token;
    public $password;
    //
    private $_user;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['reset_token', 'password'], 'required'],
            ['password', 'match', 'pattern' => '/^(?=(.*[A-Za-z]){2})(?=.*[0-9])[A-Za-z0-9@$#]{8,32}$/', 'message' => '密码过于简单'],
            ['reset_token', 'validateResetToken'],
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validateResetToken($attribute) {
        if (!$this->hasErrors()) {
            if (!$this->getUser()) {
                $this->addError($attribute, '密码重置令牌不正确');
            }
        }
    }

    /**
     * Finds user by [[username]]
     *
     * @return \api\models\UserCompatibleModel|null
     */
    protected function getUser() {
        if ($this->_user === null) {
            $this->_user = User::findByPasswordResetToken($this->reset_token);
        }
        return $this->_user;
    }

    /**
     * Signs user up.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function resetPassword() {
        if (!$this->validate()) {
            $this->dumpError('重置密码校验失败');
        }
        $user = $this->getUser();
        $user->setPassword($this->password);
        $user->removePasswordResetToken();
        return $user->save();
    }

}
